
var Dyniqx = function(){
    
    var layout, twoLayout;
    
    var drawGrid = function() {
            
       var myData, ds, colModel, grid, layout; 
            
       return {
       
            init : function() {
        
                myData = eval('[]');
    
                ds = new Ext.data.Store({
                    proxy: new Ext.data.MemoryProxy(myData),
                    reader: new Ext.data.ArrayReader({}, [
                        {name: 'query'},
                        {name: 'source'},
                        {name: 'total', type: 'int'},
                        {name: 'parsed', type: 'int'}
                    ])
                });
                ds.load();
                
                var renderQuery = function(val) {
                    return '<strong>' + val + '</strong>';
                }
                
                var renderTotal = function(val) {
                    if (val > 100) {
                        return '100+';
                    } else {
                        return val;
                    }
                }
                  
                colModel = new Ext.grid.ColumnModel([
                            {id:'query',header: "Query string", sortable: true, locked:false, renderer: renderQuery, dataIndex: 'query'},
                            {header: "Src", width: 32, sortable: true, dataIndex: 'source'},
                            {header: "Hits", width: 35, sortable: true, renderer: renderTotal, dataIndex: 'total'},
                            {header: "Results", width: 46, sortable: true, dataIndex: 'parsed'}
                        ]);
                
                grid = new Ext.grid.Grid('grid', {
                            ds: ds,
                            cm: colModel,
                            autoExpandColumn: 'query',
                            autoHeight:true
                        });
                
                grid.render();
                grid.getSelectionModel().selectFirstRow();
            },
                
            update : function() {     
                var dataPool = $F('dumping');
                ds.loadData(eval(dataPool));
            }
        }
    }();
    
    return {
        
        init : function(){

            layout = new Ext.BorderLayout($('container'), {
                north: {
                    split:false,
                    initialSize: 80,
                    titlebar: false
                },
                south: {
                    split:false,
                    initialSize: 45,
                    titlebar: false,
                    collapsible: false,
                    animate: false
                },
                east: {
                    split:false,
                    initialSize: 300,
                    titlebar: false,
                    autoScroll:true
                },
                center: {
                    autoScroll:false,
                    titlebar: false
                }
            });
                        

            layout.beginUpdate();
            layout.add('north', new Ext.ContentPanel('header'));
            layout.add('south', new Ext.ContentPanel('footer'));          
            layout.add('east', new Ext.ContentPanel('options'));
            
            innerLayout = new Ext.BorderLayout('main', {
                north: {
                    split:false,
                    initialSize: 280,
                    titlebar: false
                    },
                center: {
                    autoScroll:true,
                    titlebar:false
                    } 
            });
            
            innerLayout.add('north', new Ext.ContentPanel('step-one'));
            innerLayout.add('center', new Ext.ContentPanel('step-two'));
            
            layout.add('center', new Ext.NestedLayoutPanel(innerLayout));          
            layout.endUpdate();
            
            drawGrid.init();

        },
        
        
                sendMessage : function() {
                    if ($F('query')) {
                        SessionWrapper.addQuery($F('query'));
                        $('pool').show();
                        new Insertion.Bottom('restricted', '<li onclick="Dyniqx.restrictQuery(this);">' + $F('query') + '</li>');
                        SessionWrapper.invokeExpertSearch($F('query'), Dyniqx.invokeExpertSearch);
                        $('query').value = "";                        
                    }
                },
                
                displayResults : function() {
                
                    var ref = "";
                    
                    if ($F('refine')) {
                        ref = $F('refine');
                    } else {
                        ref = "alldocs";
                    }
                    
                    $('refined-results').innerHTML = "";
                    $$('ul#restricted li').each(function (el) {
                        el.removeClassName('restrict');
                    });
                    
                    SessionWrapper.retrieveResults(ref, Dyniqx.doResultList);
                },
                
                resetPool : function() {
                        $('pool').hide();
                        $('query').value = "";
                        $('refine').value = "";
                        SessionWrapper.resetPool();
                        $('terms').innerHTML = "";                        
                        $('refined-results').innerHTML = "";
                        $('restricted').innerHTML = "";
                        $('displayed-results-counter').innerHTML = '0';
                        $('new-results-counter').innerHTML = '0';
                        $('new-results').hide();
                        $('no-results').show();
                },
                
                updateGrid : function() {
                    drawGrid.update();
                },
                
                showNewResults : function() {
                    $('new-results-counter').innerHTML = $('all-results-counter').innerHTML * 1 - $('displayed-results-counter').innerHTML * 1;
                    if ($('new-results-counter').innerHTML * 1 > 0) {
                       $('new-results').show();
                       $('no-results').hide();
                    }
                },
                
                fetchNewTerms : function() {
                    $('displayed-results-counter').innerHTML = $('displayed-results-counter').innerHTML * 1 + $('new-results-counter').innerHTML * 1;
                    $('new-results-counter').innerHTML = '0';
                    $('new-results').hide();
                    $('no-results').show();
                    SessionWrapper.fetchNewTerms();
                },
                
                parseIndexedTerms : function() {
                    var dataPool = $('terms-dumping').innerHTML;
                    var hash = $H(eval("(" + dataPool + ")"));
                    var i = 0;
                    
                    if (($('displayed-results-counter').innerHTML * 1) == 0 ) $('refine').value = ''; 
                    
                    var selectedOld = $w($F('refine').replace(/~~/g, ' ').replace(/~/g, ' '));
                    var selectedNew = "";
                    var CSSclass = "";
                                          
                    $('terms').innerHTML = "";
                    
                    hash.each(function (pair) {
                        CSSclass = ""
                         if (selectedOld.member(pair.key)) {
                            selectedNew += "~" + pair.key + "~";
                            CSSclass = " active";
                        }
                            
                        new Insertion.Bottom('terms', '<span class="size-' + pair.value + CSSclass + '">' + pair.key + '</span>');
                        if (++i%10 == 0) new Insertion.Bottom('terms', '<br />');
                    });

                    var spans = $$('#terms span');
                    
                    spans.each(function(el) {
                        el.onclick = function () {
                            el.toggleClassName('active');
                            if (el.hasClassName('active')) {
                                $('refine').value = $F('refine') + '~' + el.innerHTML + '~';
                                Dyniqx.displayResults();
                            } else {
                                $('refine').value = $F('refine').replace('~' + el.innerHTML + '~', '');
                                Dyniqx.displayResults();
                            }
                        }
                    });
                    
                    $('refine').value = selectedNew;
                    Dyniqx.displayResults();
                },
                
                doResultList : function(objs) {
                
                    $('refined-results').innerHTML = "";
        
                    var results = objs.size();
                    var limited = '';
        
                    if (results >= 300) limited = ' (limited) ';
        
                    if (results != 0) {
                        new Insertion.Top('refined-results', '<p class="info">Displaying ' + results + limited + ' results...</p>');
                    }
        
                    var template_text = new Template('\
                      <li>\
                        <h3><a href="#{link}" target="_blank">#{title}</a></h3>\
                        <p class="authors">#{authors}</p>\
                        <p class="details">Available from <span class="source">#{source}</span></p>\
                        <p class="querystring">Query used: #{query}</p>\
                        <p>#{description}</p>\
                        <p class="score">Lucene calculated score: #{score}</p>\
                        <p class="rank">Original rank per thread: #{rank}</p>\
                      </li>\
                    ');


                    var template_image = new Template('\
                      <li>\
                        <h3><a href="#{internal}" target="_blank">#{abbr}</a></h3>\
                        <p class="details">Available from <span class="source">#{source}</span></p>\
                        <p class="querystring">Query used: #{query}</p>\
                        <div class="image float-manager">\
                            <a href="#{link}" target="_blank">\
                                <img width="#{thumbWidth}" height="#{thumbHeight}" src="#{thumbUrl}" title="#{id}" alt="Go to fullsize image" />\
                            </a>\
                            <p class="details">#{width} x #{height} | #{fileFormat} | #{fileSize} bytes</p>\
                            <p>#{summary}</p>\
                        </div>\
                        <p class="score">Lucene calculated score: #{score}</p>\
                        <p class="rank">Original rank per thread: #{rank}</p>\
                      </li>\
                    ');

                    var template_video = new Template('\
                      <li>\
                        <h3><a href="#{internal}" target="_blank">#{title}</a></h3>\
                        <p class="details">Available from <span class="source">#{source}</span></p>\
                        <p class="querystring">Query used: #{query}</p>\
                        <div class="image float-manager">\
                            <a href="#{link}" target="_blank">\
                                <img width="#{thumbWidth}" height="#{thumbHeight}" src="#{thumbUrl}" title="#{id}" alt="Play movie" />\
                            </a>\
                            <p class="details">#{fileFormat} | #{fileSize} seconds</p>\
                            <p>#{summary}</p>\
                        </div>\
                        <p class="score">Lucene calculated score: #{score}</p>\
                        <p class="rank">Original rank per thread: #{rank}</p>\
                      </li>\
                    ');

                    var evaluation;
                    
                    objs.each( function(obj) {
                    
                        if (obj.description.empty()) {
                            obj.description = 'Not available';
                        } else {
                            obj.description = obj.description.truncate(250, '...');
                        }
                      
                        if (obj.source == 'PbM') {
                            obj.source = 'PubMed';
                        } else if (obj.source == 'Int') {
                            obj.source = 'Intute';
                        } else if (obj.source == 'GSc') {
                            obj.source = 'Google Scholar';
                        } else if (obj.source == 'PrX') {
                            obj.source = 'PerX';
                        } else if (obj.source == 'GIm') {
                            obj.source = 'Google Images';
                        } else if (obj.source == 'YIm') {
                            obj.source = 'Yahoo Images';
                        } else if (obj.source == 'GVi') {
                            obj.source = 'Google Video';
                        }
                       
                        if (obj.source != 'Google Scholar') {
                            obj.authors = obj.authors + ' - ' + obj.journal + ', ' + obj.date;
                        } 

                        obj.abbr = obj.internal.truncate(80, '...');

                        if (obj.type == 'video') {
                            obj.thumbWidth /= 2;
                            obj.thumbHeight /= 2;
                        }
  
                        if (obj.type == 'text') {
                            evaluation = template_text.evaluate(obj);
                        } else if (obj.type == 'image') {
                            evaluation = template_image.evaluate(obj);
                        } else if (obj.type == 'video') {
                            evaluation = template_video.evaluate(obj);
                        } 
                             
                        new Insertion.Bottom('refined-results', evaluation);
                    });
                                        
                    $$('ul#refined-results li').each(function (obj) {
                        obj.onmouseover = function() {
                            this.addClassName('highlight');
                        };
                        obj.onmouseout = function() {
                            this.removeClassName('highlight');
                        };
                     });
                                    
                    $$('ul#restricted li').each(function (obj) {
                        obj.removeClassName('restrict');
                    });

                    $$('dl#engines input').each(function (obj) {
                        obj.checked = true;
                     });

                    if (results == 0) {
                        new Insertion.Bottom('refined-results', '<p class="info">No results matching current filtering.</p>');
                    } 
                    
                },
                                
                restrictQuery : function(obj) {

                    obj.toggleClassName('restrict');
                    $$('#refined-results li .querystring').each(function(o) {
                        if (o.innerHTML == ("Query used: " + obj.innerHTML)) {
                            if (obj.hasClassName('restrict')) {
                                o.up().hide();
                            } else {
                                o.up().show();
                            }
                        }
                    });
                    
                },
                
                manageEngines : function(obj) {
                    
                    $$('#refined-results li .source').each(function(o) {
                        if (o.innerHTML == obj.value) {
                            if (obj.checked) {
                                o.up().up().show();
                            } else { 
                                o.up().up().hide();
                            }
                        }
                    });
                },
                
                invokeExpertSearch : function(objs) {
                    objs = eval(objs);
                    limit = (objs.size() > 20) ? 20 : objs.size();
                    objs = objs.slice(0, limit);
                    
                    if (objs.size() > 0) {
                        $('expertsearch').update('Experts for last query: ');
                        objs.each( function(obj) {                    
                            new Insertion.Bottom('expertsearch', '<a href="http://scholar.google.co.uk/scholar?q=author:' + obj.name.replace(' ','-') + '" target="_blank">' + obj.name + ' (' + obj.score + ')</a>');
                        });
                    } else {
                        $('expertsearch').update('No expert found for last query.');
                    }
                }
    }
}();

Ext.onReady(Dyniqx.init, Dyniqx);
